"use strict";
var BaseCom_1 = require('./../BaseCom');
var crc = require('crc');
/** 操作倾角计的串口类,该类在创建时自动打开指定的串口 */
class AngleCom extends BaseCom_1.BaseCom {
    /*
    * 构造函数
    * @param portName 串口名称,无视大小写
    */
    constructor(portName) {
        super(portName);
        /** 是否完成本次串口数据读取操作 */
        this._dataComplete = () => {
            if (this._tempBuffer.length !== 11)
                return false;
            else
                return true;
        };
        /** 处理本次的数据 */
        this._proccessData = () => {
            let validate = this._validateSurveyResult(); //验证CRC和长度
            if (validate) {
                let resultData = new MeasureResult();
                resultData.x = this._tempBuffer.readInt16BE(3);
                resultData.y = this._tempBuffer.readInt16BE(5);
                resultData.t = this._tempBuffer.readInt16BE(7);
                //返回真正的resultData,当前测量完成;
                this._defer.resolve(resultData);
            }
            else {
                this._defer.resolve(null);
            }
        };
    }
    /**
    * 验证测量结果是否正确
    * @return 是否符合格式要求,true为合适,false为不合适
    */
    _validateSurveyResult() {
        if (this._tempBuffer.length !== 11)
            return false;
        let crcbuf = this._getCRC(this._tempBuffer);
        if (crcbuf.equals(this._tempBuffer))
            return true;
        return false;
    }
    /**
    * 注意,这个buffer是一个完整的buffer,带有两个字节的CRC-16校验码
    * 验证的时候只验证从0到length-3的位置,忽略length-2、length-1的CRC-16的部分.
    * @param buffer 要验证的buffer
    * @return buffer 重新计算CRC-16校验码后的完整的buffer
    */
    _getCRC(buffer) {
        let len = buffer.length;
        let tempbuf = buffer.slice(0, len - 2);
        let crcbuf = new Buffer(2);
        crcbuf.writeUInt16BE(crc.crc16modbus(tempbuf), 0);
        buffer[len - 1] = crcbuf[0];
        buffer[len - 2] = crcbuf[1];
        return buffer;
    }
    /**
     * 测量前的准备工作
     * @param deviceId - 测量仪器的编号
     */
    _sendSurveyCmd(deviceId) {
        let buffer = new Buffer([deviceId, 0x03, 0x00, 0x00, 0x00, 0x03, 0x05, 0xcb]);
        buffer = this._getCRC(buffer);
        this.port.write(buffer);
    }
    /**
     * 发送测量命令
     * @param deviceId - 测量仪器的编号
     */
    survey(deviceId) {
        this._preSurvey(); //准备工作
        this._surveyTimeout(); //开始计算超时
        this._sendSurveyCmd(deviceId);
        return this._defer.promise;
    }
}
exports.AngleCom = AngleCom;
class MeasureResult {
    constructor() {
        this.x = null;
        this.y = null;
        this.t = null;
    }
}
exports.MeasureResult = MeasureResult;
